import { BrowserRouter as Router, Routes, Route, Link, useNavigate } from 'react-router-dom'
import { useState, useEffect } from 'react'
import { AppBar, Toolbar, IconButton, Menu, MenuItem, Typography, Box } from '@mui/material'
import MenuIcon from '@mui/icons-material/Menu'
import MovieList from './components/MovieList'
import MovieManagement from './components/MovieManagement'
import AuthPage from './components/AuthPage'
import OrderList from './components/OrderList'
import OrderDetail from './components/OrderDetail'
import UserManagement from './components/UserManagement';
import './App.css'
import RequireAuth from './components/RequireAuth';

function AppContent() {
  const navigate = useNavigate();
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [username, setUsername] = useState('');
  const [isAdmin, setIsAdmin] = useState(false);
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  
  const handleMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
  };

  useEffect(() => {
    const userStr = localStorage.getItem('user');
    if (userStr) {
      const user = JSON.parse(userStr);
      setIsLoggedIn(user.isLoggedIn);
      setUsername(user.username);
      setIsAdmin(user.role === 'admin');
    }
  }, []);

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    setIsLoggedIn(false);
    setUsername('');
    setIsAdmin(false);
    navigate('/');
  };

  return (
    <div className="app">
      <AppBar position="static" color="transparent" elevation={0}>
        <Toolbar sx={{ justifyContent: 'flex-end' }}>
          {isLoggedIn ? (
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Typography variant="body1" sx={{ mr: 2, color: '#ffffff', textShadow: '1px 1px 2px rgba(0,0,0,0.5)', fontWeight: 500 }}>
                欢迎，{username}
              </Typography>
              <IconButton
                size="large"
                edge="end"
                color="inherit"
                aria-label="menu"
                onClick={handleMenuOpen}
                sx={{
                  color: '#1976d2',
                  '&:hover': {
                    backgroundColor: 'rgba(25, 118, 210, 0.04)'
                  }
                }}
              >
                <MenuIcon />
              </IconButton>
              <Menu
                anchorEl={anchorEl}
                open={Boolean(anchorEl)}
                onClose={handleMenuClose}
                transformOrigin={{ horizontal: 'right', vertical: 'top' }}
                anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
                PaperProps={{
                  elevation: 3,
                  sx: {
                    mt: 1,
                    minWidth: 180,
                    '& .MuiMenuItem-root': {
                      py: 1
                    }
                  }
                }}
              >
                <MenuItem onClick={() => { navigate('/'); handleMenuClose(); }}>
                  首页
                </MenuItem>
                <MenuItem onClick={() => { navigate('/orders'); handleMenuClose(); }}>
                  我的订单
                </MenuItem>
                {isAdmin && (
                  <div>
                    <MenuItem 
                      onClick={() => { navigate('/movie-management'); handleMenuClose(); }}
                      sx={{ color: '#2e7d32' }}
                    >
                      电影管理
                    </MenuItem>
                    <MenuItem 
                      onClick={() => { navigate('/users'); handleMenuClose(); }}
                      sx={{ color: '#2e7d32' }}
                    >
                      用户管理
                    </MenuItem>
                  </div>
                )}
                <MenuItem 
                  onClick={() => { handleLogout(); handleMenuClose(); }}
                  sx={{ color: '#d32f2f' }}
                >
                  退出
                </MenuItem>
              </Menu>
            </Box>
          ) : (
            <Link to="/auth" style={{ textDecoration: 'none' }}>
              <Box sx={{ display: 'flex', alignItems: 'center' }}>
                <Typography variant="body1" sx={{ mr: 2, color: '#ffffff', textShadow: '1px 1px 2px rgba(0,0,0,0.5)', fontWeight: 500 }}>
                  登录/注册
                </Typography>
                <IconButton
                  size="large"
                  edge="end"
                  sx={{
                    color: '#1976d2',
                    '&:hover': {
                      backgroundColor: 'rgba(25, 118, 210, 0.04)'
                    }
                  }}
                >
                  <MenuIcon />
                </IconButton>
              </Box>
            </Link>
          )}
        </Toolbar>
      </AppBar>
      <Routes>
        <Route path="/" element={<MovieList />} />
        <Route path="/auth" element={<AuthPage setIsLoggedIn={setIsLoggedIn} setUsername={setUsername} />} />
        <Route path="/orders" element={<OrderList />} />
        <Route path="/order/:orderId" element={<OrderDetail />} />
        <Route path="/movie-management" element={<MovieManagement />} />
        <Route path="/users" element={
          <RequireAuth>
            <UserManagement />
          </RequireAuth>
        } />
      </Routes>
    </div>
  )
}

function App() {
  return (
    <Router>
      <AppContent />
    </Router>
  )
}

export default App
